import Vue from 'vue'
import Router from 'vue-router'
import Login from '../components/Login.vue'
import Main from '../components/Main.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/Users.vue'
import Rights from '../components/role/Rights.vue'
import Roles from '../components/role/Roles.vue'
import Cate from '../components/goods/Cate.vue'
import Goods from '../components/goods/Goods.vue'
import Add from '../components/goods/Add.vue'
import Params from '../components/goods/Params.vue'

Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes: [
    {path: '/', redirect: '/login'},
    {path: '/login', component: Login},
    {
      path: '/main',
      component: Main,
      redirect: '/welcome',
      children: [
        {path: '/welcome', component: Welcome},
        {path: '/users', component: Users},
        {path: '/rights', component: Rights},
        {path: '/roles', component: Roles},
        {path: '/categories', component: Cate},
        {path: '/goods', component: Goods},
        { path: '/goods/add', component: Add },
        {path: '/params', component: Params}
      ]}
  ]
})

// 挂载导航守卫，每次路由跳转前做判断
router.beforeEach((to, from, next) => {
  /**
   * to为将要跳转的路径，from 代表从那个路径跳转而来，
   * next 表示放行函数，所带参数则表示强制跳转的路径
   */
  // 1、登录、注册、重置密码页面直接放行
  if (to.path === '/login' ||
  to.path === '/regist' ||
  to.path === '/resetPwd') {
    return next()
  }
  // 2、需要登录的页面，验证token
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) {
    // token为空，跳转到主页
    return next('/login')
  }
  // 验证token内容TODO

  next()
})

export default router
